package com.pcbly.web.persistence.client;
 
import java.util.List; 

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.pcbly.web.bean.client.CustomerBean;
import com.pcbly.web.bean.client.CustomerListBean;
import com.pcbly.web.components.hibernate.support.Page;
import com.pcbly.web.components.utils.LightsoftStringUtils;
import com.pcbly.web.components.utils.random.GUID;
import com.pcbly.web.persistence.HibernateBaseDao;

@SuppressWarnings("unchecked")
public class CustomerHibernateDao extends HibernateBaseDao<CustomerBean>
		implements CustomerDao {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4077319785337224990L;

	public CustomerHibernateDao() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected Class<CustomerBean> getEntityClass() {
		return CustomerBean.class;
	}

	@Override
	public CustomerBean saveCustomerBean(CustomerBean bean) throws Exception {
		// TODO Auto-generated method stub
		String id = (new GUID()).toString();
		bean.setId(id);
		getHibernateTemplate().save(bean);
		return bean;
	}

	@Override
	public Page<CustomerListBean> findCustomerBeanByCond(CustomerBean bean,
			Page<CustomerListBean> page, String orderByName, boolean asc)
			throws Exception {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder();
		sb.append("select * from v_customer where RECYCLED=0 ");
		// Criteria criteria = getSession().createCriteria(CustomerBean.class);
		if (!(bean == null)) {
			if (!(bean.getClientName() == null || "".equals(bean
					.getClientName().trim()))) {
				// criteria.add(Restrictions.like("clientName", bean
				// .getClientName()));
				sb.append(" and CLIENTNAME like '%");
				sb.append(bean.getClientName().trim());
				sb.append("%'");
			}

			if (!(bean.getClientCode() == null
					|| "0".equals(bean.getClientCode()) || "".equals(bean
					.getClientCode().trim()))) {
				// criteria.add(Restrictions.like("clientCode", bean
				// .getClientCode()));
				sb.append(" and CLIENTCODE like '%");
				sb.append(bean.getClientCode().trim());
				sb.append("%'");
			}
			if (!(bean.getMainTelephone() == null
					|| "0".equals(bean.getMainTelephone()) || "".equals(bean
					.getMainTelephone().trim()))) {
				// criteria.add(Restrictions.like("mainTelephone", bean
				// .getMainTelephone()));
				sb.append(" and MAINTELEPHONE like '%");
				sb.append(bean.getMainTelephone().trim());
				sb.append("%'");
			}
			if (!(bean.getClientType() == null
					|| "0".equals(bean.getClientType()) || "".equals(bean
					.getClientType().trim()))) {
				// criteria.add(Restrictions.like("clientType", bean
				// .getClientType()));
				sb.append(" and CLIENTTYPEID like '%");
				sb.append(bean.getClientType().trim());
				sb.append("%'");
			}
			if (!(bean.getClientLevel() == null
					|| "0".equals(bean.getClientLevel()) || "".equals(bean
					.getClientLevel().trim()))) {
				// criteria.add(Restrictions.like("clientLevel", bean
				// .getClientLevel()));
				sb.append(" and CLIENTLEVELID like '%");
				sb.append(bean.getClientLevel().trim());
				sb.append("%' ");
			}
			if (!(bean.getClientSource() == null
					|| "0".equals(bean.getClientSource()) || "".equals(bean
					.getClientSource().trim()))) {
				// criteria.add(Restrictions.like("clientSource", bean
				// .getClientSource()));
				sb.append(" and CLIENTSOURCEID like '%");
				sb.append(bean.getClientSource().trim());
				sb.append("%'");
			}
			if (!(bean.getClientKind() == null
					|| "0".equals(bean.getClientKind()) || "".equals(bean
					.getClientKind().trim()))) {
				// criteria.add(Restrictions.like("clientKind", bean
				// .getClientKind()));
				sb.append(" and CLIENTKINDID like '%");
				sb.append(bean.getClientKind().trim());
				sb.append("%'");
			}
			if (!(bean.getClientTrade() == null
					|| "0".equals(bean.getClientTrade()) || "".equals(bean
					.getClientTrade().trim()))) {
				// criteria.add(Restrictions.like("clientTrade", bean
				// .getClientTrade()));
				sb.append(" and CLIENTTRADEID like '%");
				sb.append(bean.getClientTrade().trim());
				sb.append("%'");
			}
			// criteria.add(Restrictions.eq("recycled", "0"));
		}
		if (asc) {
			// criteria.addOrder(Order.asc(orderByName));
			sb.append(" order by  ");
			sb.append(orderByName);
			sb.append(" ");
		} else {
			// criteria.addOrder(Order.desc(orderByName));
			sb.append(" order by  ");
			sb.append(orderByName);
			sb.append(" desc ");
		}
		Object obj = getSession().createSQLQuery(
				"select count(*)  " + removeSelect(removeOrders(sb.toString())) + " ").uniqueResult();
		if (obj == null) {
			obj = "0";
		}
		
		page.setTotalCount(Integer.parseInt(String.valueOf(obj)));
		
		if(page.getTotalCount()<1){
			return page;
		}
		
		int first = page.getFirst();
		int lpage = first + page.getPageSize();
		if (lpage > page.getTotalCount()) {
			lpage = page.getTotalCount();
		}
		List<CustomerListBean> customerBeans = getSession().createSQLQuery(
				sb.toString()).addEntity(CustomerListBean.class).list().subList(first, lpage);
		// List<CustomerBean> customerBeans = criteria.list();
//		page.setTotalCount(customerBeans.size());
//		
		page.setResult(customerBeans);
		return page;
	}

	@Override
	public void deleteCustomerBeanById(String id) throws Exception {
		// TODO Auto-generated method stub
		
		StringBuilder sb = new StringBuilder(
				"update t_customer set RECYCLED='1' where ID");
		if (id.indexOf(",") > 0) {
			id = id.replaceAll("'", "''");
			id = id.replaceAll(",", "','");
			sb.append(" in('").append(id).append("')");
		} else {
			sb.append("='").append(id.replaceAll("'", "''")).append("'");
		}
		getSession().createSQLQuery(sb.toString()).executeUpdate();
	}

	@Override
	public List<CustomerBean> findCustomerBeansByName(String name)
			throws Exception {
		// TODO Auto-generated method stub
		Criteria criteria = getSession().createCriteria(CustomerBean.class);
		criteria.add(Restrictions.eq("recycled", "0")); 
		if(!LightsoftStringUtils.nullOrBlank(name)){  
			criteria.add(Restrictions.like("clientName", name,MatchMode.END));
		}
		criteria.addOrder(Order.asc("clientName")); 
		
		return criteria.list();
	} 

}
